package com.cmy.framework.mvvm.binding.command

/**
 * @name:
 *  BindingCommand
 * @package:
 *  com.cmy.framework.mvvm.binding.command
 * @date:
 *  2023/3/211:16
 * @author
 *    cmy
 * @description
 * 执行的命令回调, 用于ViewModel与xml之间的数据绑定
 */
open class BindingCommand<T> {
    private var execute: BindingAction? = null
    private var consumer: BindingConsumer<T>? = null
    private var canExecute0: BindingFunction<Boolean>? = null

    constructor(execute: BindingAction) {
        this.execute = execute
    }

    constructor(execute: BindingConsumer<T>) {
        this.consumer = execute
    }

    constructor(execute: BindingAction, canExecute0: BindingFunction<Boolean>) {
        this.execute = execute
        this.canExecute0 = canExecute0
    }

    constructor(execute: BindingConsumer<T>, canExecute0: BindingFunction<Boolean>) {
        consumer = execute
        this.canExecute0 = canExecute0
    }

    constructor()

    /**
     * 执行BindingAction命令
     */
    fun execute() {
        execute?.let {
            if (canExecute0()){
                it.call()
            }
        }
    }

    /**
     * 执行带泛型参数的命令
     *
     * @param parameter 泛型参数
     */
    fun execute(parameter: T) {
        consumer?.let {
            if (canExecute0()){
                it.call(parameter)
            }
        }
    }

    /**
     * 是否需要执行
     *
     * @return true则执行, 反之不执行
     */
    private fun canExecute0(): Boolean {
        var bool = true
        canExecute0?.let {
            bool = it.call()
        }
        return bool
    }

}